package bap_server;
import questiondata.Question;
import java.util.*;
import java.io.*;

import questiondata.Question;
public class QuestionManager {
	Vector questionVec;
	int question_num;
	String data_file_name = "ques_data";
	public QuestionManager() {
		questionVec = new Vector();
		question_num = 0;
		read_data();
	}
	public void addQuestion(Question ques) {
		ques.setId(question_num);
		questionVec.add(ques);
		question_num ++;
		try {
			save_data(ques);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
	public void loadQuestion(Question ques) {
		ques.setId(question_num);
		questionVec.add(ques);
		question_num ++;
	}
	public Question getQuestion(int pos) {
		Question result = (Question)questionVec.get(pos);
		return result;
	}
	public int save_data(Question ques) throws IOException{
		FileWriter fr = new FileWriter(data_file_name, true);
		fr.write(ques.to_save_String());
		fr.close();
		return 0;
	}
	public void read_data() {
		File file = new File(data_file_name);
		BufferedReader reader = null;
		int cnt = 0;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				System.out.println(tempString);
				String array[] = tempString.split("\t");
				Question ques = new Question("test");
				ques.setId(cnt++);
				ques.setTitle(array[0]);
				ques.setWeight(Integer.parseInt(array[1]));
				ques.setRight_ans(Integer.parseInt(array[2]));
				ques.setAns_num(Integer.parseInt(array[3]));
				String choices[] = new String[ques.getAns_num()];
				for (int i = 0; i < ques.getAns_num(); i++) {
					choices[i] = array[4 + i];
				}
				ques.setAns_data(choices);
				loadQuestion(ques);
				System.out.println(ques.getId());
				System.out.println(ques.to_String());
			}
			reader.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	Question choose_Question(int num) {
		if (num < 0 || num >question_num) {
			return getQuestion(0);
		}
		Random rnd = new Random();
		int pos = num;
		while (pos == num) {
			pos = rnd.nextInt(question_num); 
		}
		return getQuestion(pos);
	}
}
